import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'

// 创建实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    const timeout = 20000000000
    const loginTime = localStorage.getItem('loginTime')
    const now = Date.now()
    if (now - loginTime > timeout) {
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('token 失效'))
    }
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
})

// 响应拦截器
service.interceptors.response.use(res => {
  // console.log('12', res)
  const { success, data, message } = res.data
  if (success) {
    console.log('数据获取成功')
    return data
  } else {
    console.log('数据获取失败')

    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, err => {
  if (err.response && err.response.data && err.response.data.code === 10002) {
    store.dispatch('user/logout')
    router.push('/login')
  }
  // console.dir('26', err)
  Message.error(err.message)
  return Promise.reject(new Error(err.message))
}
)

export default service
